package cn.zwk.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

@Slf4j
@Service
public class HttpSenderService {
    
    private final HttpClient httpClient;
    
    public HttpSenderService() {
        this.httpClient = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();
    }
    
    public void sendData(String url, String data, boolean waitResponse) {
        try {
            log.debug("准备发送请求到: {}", url);
            log.debug("发送数据内容:\n{}", data);
            
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .timeout(Duration.ofSeconds(30))
                    .header("Content-Type", "text/plain; charset=utf-8")
                    .POST(HttpRequest.BodyPublishers.ofString(data))
                    .build();
            
            if (waitResponse) {
                HttpResponse<String> response = httpClient.send(request, 
                        HttpResponse.BodyHandlers.ofString());
                
                log.info("数据发送完成: statusCode={}, responseBody={}", 
                        response.statusCode(), response.body());
                
                if (response.statusCode() != 200 && response.statusCode() != 204) {
                    log.warn("数据发送可能失败: statusCode={}, responseBody={}", 
                            response.statusCode(), response.body());
                }
            } else {
                // 异步发送，不等待响应
                httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                        .thenAccept(response -> {
                            log.debug("异步发送完成: statusCode={}", response.statusCode());
                            if (response.statusCode() != 200 && response.statusCode() != 204) {
                                log.warn("异步发送可能失败: statusCode={}, responseBody={}", 
                                        response.statusCode(), response.body());
                            }
                        })
                        .exceptionally(throwable -> {
                            log.error("异步发送数据时发生错误: {}", throwable.getMessage(), throwable);
                            return null;
                        });
            }
        } catch (Exception e) {
            log.error("发送数据时发生错误: {}", e.getMessage(), e);
        }
    }
    
    public void sendData(String url, String data) {
        sendData(url, data, true);
    }
}